//
//  NetworkListener.swift
//  ADKit
//
//  Created by Adoma on 2020/10/25.
//

import Foundation
import Alamofire
import RxSwift

/// by ADKit
public struct NetworkListener {
    
    public enum Status {
        case unknown
        case none
        case wifi
        case wwan
    }
    
    public static let shared = NetworkListener()
    
    public let status = BehaviorSubject(value: Status.none)
    
    public let publicIP = BehaviorSubject<String?>(value: nil)
    private let publicIPRequest = SerialDisposable()

    let reachability = NetworkReachabilityManager()
    
    public func start(provider: String = "https://ifconfig.co/json") {
        
        reachability?.startListening(onUpdatePerforming: { status in
            switch status {
            case .reachable(let type):
                if type == .cellular {
                    self.status.onNext(.wwan)
                } else {
                    self.status.onNext(.wifi)
                }
                self.getPublicIp(provider: provider)
            case .unknown:
                self.status.onNext(.unknown)
            default:
                self.status.onNext(.none)
            }
        })
        
    }
    
    func getPublicIp(provider: String) {
        let cancel = SingleAssignmentDisposable()
        self.publicIPRequest.disposable = cancel

        let request = AF.request(provider)
            .responseString { [weak cancel] response in
                guard let cancel, !cancel.isDisposed else { return }
                self.publicIP.onNext(response.value)
            }

        cancel.setDisposable(Disposables.create {
            request.cancel()
        })
    }

}
